<?php

if(!isset($_SESSION)) {
    session_start();
}

use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use utils\out;

/**请求登录**/
$app->post('/bd/login', function (Application $app, Request $request) {
	$name = $request->get('name');
	$password = $request->get('password');

	if($name === 'master' && $password === '111qqq') {
		$_SESSION['userinfo'] = array("name"=>$name);
		return $app->json(array("success"=>true, "result"=>"ok"));
	} else {
		return $app->json(array("success"=>false, "result"=>"用户名或密码错误"));
	}
});


/**后台首页*/
$app->get('/bd/index', function (Application $app) {
	if(!$_SESSION || !$_SESSION['userinfo']) {
		return $app->redirect('/login');
	}
	return $app['twig']->render('bd_index.html');
});


/**上传图片*/
$app->post('/bd/upload', function (Application $app, Request $request) {
	if(!$_SESSION || !$_SESSION['userinfo']) {
		return $app->redirect('/login');
	}

	if ((($_FILES["wangEditorH5File"]["type"] == "image/gif")
		|| ($_FILES["wangEditorH5File"]["type"] == "image/jpeg")
		|| ($_FILES["wangEditorH5File"]["type"] == "image/pjpeg"))
		|| ($_FILES["wangEditorH5File"]["type"] == "image/png")) { 

		if ($_FILES["wangEditorH5File"]["error"] > 0) {
		  		return new Response("error|" . $_FILES["wangEditorH5File"]["error"]);
		} else {
	   		if ($_FILES["wangEditorH5File"]["size"] > 1000*1024) {// 1M
	   			return new Response("error|图片大小不能大于1M");
	   		}

	   		$fileName = $_FILES["wangEditorH5File"]["name"];
	   		$tmp = explode(".", $fileName);
	   		$suffix = '';
	   		if(count($tmp) > 1) {
	   			$suffix = '.' . $tmp[count($tmp)-1];
	   		}
	   		$fileName = "/files/editor/" . getRandId() . $suffix;
	   		$filePath = $_SERVER['DOCUMENT_ROOT'] . $fileName;
		    move_uploaded_file($_FILES["wangEditorH5File"]["tmp_name"], $filePath);
	      	return new Response($fileName);
		}
	} else {
	  	return new Response("error|不支持的文件类型");
	}
});